package logic

import (
	"card/app/models"
	"card/dao"
	"context"
	"github.com/pkg/errors"
)

type MemberLevelLogic struct {
	ctx context.Context
}

func NewMemberLevelLogic(ctx context.Context) *MemberLevelLogic {
	return &MemberLevelLogic{ctx: ctx}
}

// 根据pid查找所有的父类并聚合，其中grade是设置的代理层级，如果你只需要设置三级代理grade就是3
func (m *MemberLevelLogic) GetTeamList(pid, userId int64, level, grade, totalGrade int) ([]models.MemberTeamLevel, error) {
	arr := make([]models.MemberTeamLevel, 0)
	info := models.MemberTeamLevel{}
	memberModel := models.NewMember(m.ctx)
	memberInfo, err := memberModel.One(dao.WithWhere("id = ?", pid))
	if err != nil {
		return nil, errors.WithStack(err)
	}
	if memberInfo.ID > 0 {
		if grade > 0 && totalGrade > grade {
			return arr, nil
		}
		if grade > 0 {
			totalGrade = totalGrade + 1
		}
		level = level + 1
		info.Pid = pid
		info.UserID = userId
		info.Level = level
		arr = append(arr, info)
		list, err := m.GetTeamList(memberInfo.Pid, memberInfo.ID, level, grade, totalGrade)
		if err != nil {
			return nil, errors.WithStack(err)
		}
		return append(arr, list...), nil
	}
	return arr, nil
}
